﻿#region Copyright (c) 2008 plexBB Team
/*  Copyright (c) 2008 plexBB Team
 *  
 *  This file is free software: you may copy, redistribute and/or modify it  
 *  under the terms of the GNU General Public License as published by the  
 *  Free Software Foundation, either version 2 of the License, or (at your  
 *  option) any later version.  
 *  
 *  This file is distributed in the hope that it will be useful, but  
 *  WITHOUT ANY WARRANTY; without even the implied warranty of  
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU  
 *  General Public License for more details.  
 *  
 *  You should have received a copy of the GNU General Public License  
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */
#endregion

using System;
using System.ComponentModel;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Web.UI;
using System.Xml;
using System.Xml.Xsl;
using PlexBB.Controls;
using PlexBB.Data;
using PlexBB.Install;

namespace PlexBB
{
    [ToolboxData(@"<{0}:PlexBB runat=""server""></{0}:PlexBB>")]
    public class PlexBB : Control
    {
        private readonly PlexBBContext _plexBBContext;
        //private const string _currentPlexBBContextKey = "PlexBB_Control";
        //private User _user;

        public PlexBB()
        {
            // initialize PlexBBContext object
            _plexBBContext = new PlexBBContext(this);
        }

        //private PlexBBContext PlexBBContext
        //{
        //    get
        //    {
        //        // cache PlexBBContext to avoid numerous searches through HttpContext.Items collection
        //        return _plexBBContext ?? (_plexBBContext = PlexBBContext.Current);
        //    }
        //}

        public Control ActionControl { get; private set; }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            // determine action type
            Type actionType;
            switch (_plexBBContext.RequestAction.Name)
            {
                case null:
                case "idx":
                    actionType = typeof(Controls.ForumListBody);
                    break;
                case "acp":
                    actionType = typeof(Controls.Admin.Overall);
                    break;
                default:
                    throw new NotSupportedException("Not supported action type.");
            }

            // here will go authorization

            ActionControl = ForumControl.Create(actionType);
            Controls.Add(ActionControl);


            //AuthenticateRequestEventArgs args = new AuthenticateRequestEventArgs();
            //if (Context.User.Identity.IsAuthenticated)
            //{
            //    args.IsAuthenticated = true;
            //    args.Username = Context.User.Identity.Name;
            //}
            //OnAuthenticateRequest(args);

            //if (args.IsAuthenticated)
            //{
            //    // now we have username
            //    _user = Data.Users.SingleOrDefault(u => u.Name.ToLower() == args.Username.ToLower());
            //    if (_user == null)
            //    {
            //        // create dbuser with the same name, etc.
            //        _user = new User() { Name = args.Username };
            //        Data.Users.InsertOnSubmit(_user);
            //        UserEventArgs userArgs = new UserEventArgs(_user);
            //        OnCompleteRegisteredUser(userArgs);
            //    }
            //}
            //else
            //{
            //    _user = Data.Users.Single(u => u.Name == "anonymous");
            //}
            //_user.UpdateLastVisit();

            ////
            //// Add/Update current ForumSession
            ////
            //string sessionCookieKey = Config.DatabaseTablePrefix + "_plexbb_session";
            //string sessionID = null;

            //string host = Context.Request.UserHostAddress;

            //// get the cookie
            //if (Context.Request.Cookies[sessionCookieKey] != null)
            //{
            //    // try to parse cookie value
            //    try
            //    {
            //        sessionID = new Guid(Context.Request.Cookies[sessionCookieKey].Value).ToString("N");
            //    }
            //    catch (Exception) { }
            //}

            //ForumSession session;
            //if (sessionID == null)
            //{
            //    // TODO: get bots' and guests' session by host + userid;

            //    sessionID = Guid.NewGuid().ToString("N");
            //    session = null;
            //}
            //else
            //{
            //    session = Data.ForumSessions.SingleOrDefault(s => s.SessionID == sessionID);
            //}

            //if (session == null)
            //{
            //    session = new ForumSession() { SessionID = sessionID };
            //    Data.ForumSessions.InsertOnSubmit(session);
            //}
            //session.User = _user;
            //session.Host = host;
            //// TODO: also update current action, user agent, etc.

            //Context.Response.Cookies.Add(new HttpCookie(sessionCookieKey, sessionID) { Expires = DateTime.Now.AddYears(2) });
            ////StringWriter sw = new StringWriter();
            ////Data.Log = sw;
            ////try
            ////{
            //Data.SubmitChanges();
            ////}
            ////finally
            ////{
            ////    string s = sw.ToString();
            ////}


            //// perform action
            //CurrentAction.Init();
        }

        public override void Dispose()
        {
            base.Dispose();
            _plexBBContext.Dispose();
        }

        //public User User
        //{
        //    get { return _user; }
        //}

        //protected virtual void OnAuthenticateRequest(AuthenticateRequestEventArgs e)
        //{
        //    if (AuthenticateRequest != null)
        //    {
        //        AuthenticateRequest(this, e);
        //    }
        //}

        //public event AuthenticateRequestEventHandler AuthenticateRequest;
        //public event UserEventHandler CompleteRegisteredUser;

        //protected virtual void OnCompleteRegisteredUser(UserEventArgs e)
        //{
        //    if (CompleteRegisteredUser != null)
        //    {
        //        CompleteRegisteredUser(this, e);
        //    }
        //}

        //public virtual PlexBBData Data
        //{
        //    get
        //    {
        //        return PlexBBData.Current;
        //    }
        //}

        //public static PlexBB Current
        //{
        //    get
        //    {
        //        return (PlexBB)HttpContext.Current.Items[_currentPlexBBContextKey];
        //    }
        //}
    }

    //public delegate void AuthenticateRequestEventHandler(object sender, AuthenticateRequestEventArgs e);
    //public delegate void UserEventHandler(object sender, UserEventArgs e);
    //public class AuthenticateRequestEventArgs : EventArgs
    //{
    //    private string _username;
    //    private bool _isAuthenticated;
    //    public string Username
    //    {
    //        get { return _username; }
    //        set { _username = value; }
    //    }

    //    public bool IsAuthenticated
    //    {
    //        get { return _isAuthenticated; }
    //        set { _isAuthenticated = value; }
    //    }
    //}

    //public class UserEventArgs : EventArgs
    //{
    //    private readonly User _user;
    //    public UserEventArgs(User user)
    //    {
    //        _user = user;
    //    }

    //    public User User
    //    {
    //        get { return _user; }
    //    }
    //}
}
